# -*- coding: utf-8 -*-
"""
合并后的天气推送应用
"""
import os
import time
import datetime
import pytz
import random
import json
import requests
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import logging

# ----------------------------- 配置项 -----------------------------#
# API密钥配置
WEATHER_KEY = ""  # 和风天气API密钥
TIANAPI_KEY = ""  # 天眼查API密钥
SENDKEY = ""  # Server酱SENDKEY

# 邮件配置
EMAIL = "gza5210@163.com"  # 发件人邮箱
EMAIL_PASSWORD = ""  # 发件人邮箱密码
SMTP_SERVER = "smtp.163.com"  # SMTP服务器
SMTP_PORT = 465  # SMTP端口

# ----------------------------- 日志配置 -----------------------------#
# 配置logging，只输出到控制台
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler()  # 只输出到控制台
    ]
)

# 创建logger实例
logger = logging.getLogger(__name__)

# ----------------------------- 常量定义 -----------------------------#
# 日期和时间相关常量
DATE_TOMORROW = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
cur_time = time.time()
local_tz = pytz.timezone("Asia/Shanghai")
local_time = datetime.datetime.fromtimestamp(cur_time, tz=local_tz).hour

# API相关常量
WEATHER_API_BASE_URL = "https://devapi.qweather.com/v7"  # 和风天气API基础URL
IPINFO_API_URL = "https://ipinfo.io/json"  # IP信息API URL
TIANAPI_IPQUERY_URL = "https://apis.tianapi.com/ipquery/index"  # 天眼查IP查询API URL

# 天气类型相关常量
RAIN_TYPES = ['大雨', '中雨', '雷阵雨', '暴雨', '大暴雨', '特大暴雨']

# 城市ID映射
CITY_ID_MAP = {
    # 直辖市
    "北京": "101010100",
    "上海": "101020100",
    "天津": "101030100",
    "重庆": "101040100",
    
    # 华北地区
    "石家庄": "101090101",
    "唐山": "101090201",
    "秦皇岛": "101090301",
    "邯郸": "101090401",
    "邢台": "101090501",
    "保定": "101090601",
    "张家口": "101090701",
    "承德": "101090801",
    "沧州": "101090901",
    "廊坊": "101091001",
    "衡水": "101091101",
    
    "太原": "101100101",
    "大同": "101100201",
    "阳泉": "101100301",
    "长治": "101100401",
    "晋城": "101100501",
    "朔州": "101100601",
    "晋中": "101100701",
    "运城": "101100801",
    "忻州": "101100901",
    "临汾": "101101001",
    "吕梁": "101101101",
    
    "呼和浩特": "101080101",
    "包头": "101080201",
    "乌海": "101080301",
    "赤峰": "101080401",
    "通辽": "101080501",
    "鄂尔多斯": "101080601",
    "呼伦贝尔": "101080701",
    "巴彦淖尔": "101080801",
    "乌兰察布": "101080901",
    "兴安盟": "101081001",
    "锡林郭勒盟": "101081101",
    "阿拉善盟": "101081201",
    
    "济南": "101120101",
    "青岛": "101120201",
    "淄博": "101120301",
    "枣庄": "101120401",
    "东营": "101120501",
    "烟台": "101120601",
    "潍坊": "101120701",
    "济宁": "101120801",
    "泰安": "101120901",
    "威海": "101121001",
    "日照": "101121101",
    "莱芜": "101121201",
    "临沂": "101121301",
    "德州": "101121401",
    "聊城": "101121501",
    "滨州": "101121601",
    "菏泽": "101121701",
    
    "郑州": "101180101",
    "开封": "101180201",
    "洛阳": "101180301",
    "平顶山": "101180401",
    "安阳": "101180501",
    "鹤壁": "101180601",
    "新乡": "101180701",
    "焦作": "101180801",
    "濮阳": "101180901",
    "许昌": "101181001",
    "漯河": "101181101",
    "三门峡": "101181201",
    "南阳": "101181301",
    "商丘": "101181401",
    "信阳": "101181501",
    "周口": "101181601",
    "驻马店": "101181701",
    "济源": "101181801",
    
    # 东北地区
    "沈阳": "101070101",
    "大连": "101070201",
    "鞍山": "101070301",
    "抚顺": "101070401",
    "本溪": "101070501",
    "丹东": "101070601",
    "锦州": "101070701",
    "营口": "101070801",
    "阜新": "101070901",
    "辽阳": "101071001",
    "盘锦": "101071101",
    "铁岭": "101071201",
    "朝阳": "101071301",
    "葫芦岛": "101071401",
    
    "长春": "101060101",
    "吉林": "101060201",
    "四平": "101060301",
    "辽源": "101060401",
    "通化": "101060501",
    "白山": "101060601",
    "松原": "101060701",
    "白城": "101060801",
    "延边": "101060901",
    "梅河口": "101061001",
    "公主岭": "101061101",
    
    "哈尔滨": "101050101",
    "齐齐哈尔": "101050201",
    "鸡西": "101050301",
    "鹤岗": "101050401",
    "双鸭山": "101050501",
    "大庆": "101050601",
    "伊春": "101050701",
    "佳木斯": "101050801",
    "七台河": "101050901",
    "牡丹江": "101051001",
    "黑河": "101051101",
    "绥化": "101051201",
    "大兴安岭": "101051301",
    
    # 华东地区
    "南京": "101190101",
    "无锡": "101190201",
    "徐州": "101190301",
    "常州": "101190401",
    "苏州": "101190501",
    "南通": "101190601",
    "连云港": "101190701",
    "淮安": "101190801",
    "盐城": "101190901",
    "扬州": "101191001",
    "镇江": "101191101",
    "泰州": "101191201",
    "宿迁": "101191301",
    
    "杭州": "101210101",
    "宁波": "101210401",
    "温州": "101210701",
    "嘉兴": "101210301",
    "湖州": "101210201",
    "绍兴": "101210501",
    "金华": "101210801",
    "衢州": "101211001",
    "舟山": "101211101",
    "台州": "101210601",
    "丽水": "101210901",
    
    "合肥": "101220101",
    "芜湖": "101220301",
    "蚌埠": "101220201",
    "淮南": "101220401",
    "马鞍山": "101220501",
    "淮北": "101220601",
    "铜陵": "101220701",
    "安庆": "101220801",
    "黄山": "101221101",
    "滁州": "101220901",
    "阜阳": "101221201",
    "宿州": "101221301",
    "六安": "101221401",
    "亳州": "101221501",
    "池州": "101221001",
    "宣城": "101221601",
    
    "福州": "101230101",
    "厦门": "101230201",
    "莆田": "101230301",
    "三明": "101230501",
    "泉州": "101230401",
    "漳州": "101230601",
    "南平": "101230701",
    "龙岩": "101230801",
    "宁德": "101230901",
    
    "南昌": "101240101",
    "景德镇": "101240801",
    "萍乡": "101240901",
    "九江": "101240201",
    "新余": "101241001",
    "鹰潭": "101241101",
    "赣州": "101240701",
    "吉安": "101240601",
    "宜春": "101240501",
    "抚州": "101240401",
    "上饶": "101240301",
    
    # 华南地区
    "广州": "101280101",
    "韶关": "101280201",
    "深圳": "101280601",
    "珠海": "101280701",
    "汕头": "101280501",
    "佛山": "101280800",
    "江门": "101280901",
    "湛江": "101281001",
    "茂名": "101281101",
    "肇庆": "101281201",
    "惠州": "101281301",
    "梅州": "101281401",
    "汕尾": "101281501",
    "河源": "101281601",
    "阳江": "101281701",
    "清远": "101281801",
    "东莞": "101281901",
    "中山": "101282001",
    "潮州": "101282101",
    "揭阳": "101282201",
    "云浮": "101282301",
    
    "南宁": "101300101",
    "柳州": "101300301",
    "桂林": "101300401",
    "梧州": "101300501",
    "北海": "101300601",
    "防城港": "101301401",
    "钦州": "101300701",
    "贵港": "101300801",
    "玉林": "101300901",
    "百色": "101301001",
    "贺州": "101301101",
    "河池": "101301201",
    "来宾": "101301501",
    "崇左": "101301301",
    
    "海口": "101310101",
    "三亚": "101310201",
    "三沙": "101310301",
    "儋州": "101310401",
    
    # 华中地区
    "武汉": "101200101",
    "黄石": "101200201",
    "十堰": "101200301",
    "宜昌": "101200401",
    "襄阳": "101200601",
    "鄂州": "101200901",
    "荆门": "101201001",
    "孝感": "101200501",
    "荆州": "101200701",
    "黄冈": "101200801",
    "咸宁": "101201101",
    "随州": "101201201",
    "恩施": "101201301",
    "仙桃": "101201401",
    "潜江": "101201501",
    "天门": "101201601",
    "神农架": "101201701",
    
    "长沙": "101250101",
    "株洲": "101250201",
    "湘潭": "101250301",
    "衡阳": "101250401",
    "邵阳": "101250501",
    "岳阳": "101250601",
    "常德": "101250701",
    "张家界": "101250801",
    "益阳": "101250901",
    "郴州": "101251001",
    "永州": "101251101",
    "怀化": "101251201",
    "娄底": "101251301",
    "湘西": "101251401",
    
    # 西南地区
    "成都": "101270101",
    "自贡": "101270201",
    "攀枝花": "101270301",
    "泸州": "101270401",
    "德阳": "101270501",
    "绵阳": "101270601",
    "广元": "101270701",
    "遂宁": "101270801",
    "内江": "101270901",
    "乐山": "101271001",
    "南充": "101271101",
    "眉山": "101271201",
    "宜宾": "101271301",
    "广安": "101271401",
    "达州": "101271501",
    "雅安": "101271601",
    "巴中": "101271701",
    "资阳": "101271801",
    "阿坝": "101271901",
    "甘孜": "101272001",
    "凉山": "101272101",
    
    "贵阳": "101260101",
    "六盘水": "101260801",
    "遵义": "101260201",
    "安顺": "101260301",
    "毕节": "101260701",
    "铜仁": "101260601",
    "黔西南": "101260901",
    "黔东南": "101260501",
    "黔南": "101260401",
    
    "昆明": "101290101",
    "曲靖": "101290201",
    "玉溪": "101290301",
    "保山": "101290501",
    "昭通": "101290401",
    "丽江": "101291401",
    "普洱": "101290801",
    "临沧": "101290901",
    "楚雄": "101290601",
    "红河": "101290701",
    "文山": "101291001",
    "西双版纳": "101291101",
    "大理": "101291201",
    "德宏": "101291301",
    "怒江": "101291501",
    "迪庆": "101291601",
    
    "拉萨": "101140101",
    "日喀则": "101140201",
    "昌都": "101140301",
    "林芝": "101140401",
    "山南": "101140501",
    "那曲": "101140601",
    "阿里": "101140701",
    
    # 西北地区
    "西安": "101110101",
    "铜川": "101110201",
    "宝鸡": "101110301",
    "咸阳": "101110401",
    "渭南": "101110501",
    "延安": "101110601",
    "汉中": "101110701",
    "榆林": "101110801",
    "安康": "101110901",
    "商洛": "101111001",
    
    "兰州": "101160101",
    "嘉峪关": "101161101",
    "金昌": "101160301",
    "白银": "101160401",
    "天水": "101160201",
    "武威": "101160501",
    "张掖": "101160601",
    "平凉": "101160701",
    "酒泉": "101160801",
    "庆阳": "101161201",
    "定西": "101160901",
    "陇南": "101161001",
    "临夏": "101161301",
    "甘南": "101161401",
    
    "西宁": "101150101",
    "海东": "101150201",
    "海北": "101150301",
    "黄南": "101150401",
    "海南": "101150501",
    "果洛": "101150601",
    "玉树": "101150701",
    "海西": "101150801",
    
    "银川": "101170101",
    "石嘴山": "101170201",
    "吴忠": "101170301",
    "固原": "101170401",
    "中卫": "101170501",
    
    "乌鲁木齐": "101130101",
    "克拉玛依": "101130201",
    "吐鲁番": "101130501",
    "哈密": "101130401",
    "昌吉": "101130601",
    "博尔塔拉": "101130701",
    "巴音郭楞": "101130801",
    "阿克苏": "101130901",
    "克孜勒苏": "101131001",
    "喀什": "101131101",
    "和田": "101131201",
    "伊犁": "101131301",
    "塔城": "101131401",
    "阿勒泰": "101131501",
    "石河子": "101131601",
    "阿拉尔": "101131701",
    "图木舒克": "101131801",
    "五家渠": "101131901",
    "北屯": "101132001",
    "铁门关": "101132101",
    "双河": "101132201",
    "可克达拉": "101132301",
    "昆玉": "101132401",
    "胡杨河": "101132501",
    "新星": "101132601"
}

# 手动配置城市信息
CITY_NAME = "郑州"  # 城市名称

# 从CITY_ID_MAP获取城市ID
CITY_ID = CITY_ID_MAP[CITY_NAME]  # 从内置映射获取城市ID

# ----------------------------- 辅助函数 -----------------------------#
def get_clean_weather_key():
    """获取清理后的天气API密钥"""
    return WEATHER_KEY.strip("'\"").strip()

# 手动配置城市ID，无需获取城市信息

# ----------------------------- 天气数据获取模块 -----------------------------#
def Get_Weather():
    """获取实时天气"""
    clean_weather_key = get_clean_weather_key()
    weather_url = f'{WEATHER_API_BASE_URL}/weather/now?key={clean_weather_key}&location={CITY_ID}'
    try:
        weather_json = requests.get(weather_url).json()
        logger.debug(f"实时天气API响应: {weather_json}")
        weather_code = weather_json.get("code")
        if weather_code == "200":
            weather_now = weather_json.get("now", {})
            weather_text = weather_now.get("text", "未知")  # 获取天气文字
            weather_temp = weather_now.get("temp", "未知")  # 实时获取当前温度
            weather_feels_like = weather_now.get("feelsLike", "未知")  # 获取当前体感温度
            return weather_text, weather_temp, weather_feels_like
        else:
            logger.error(f"访问获取实时天气接口失败，错误码：{weather_code}，响应：{weather_json}")
            return "未知", "未知", "未知"
    except Exception as e:
        logger.error(f"获取实时天气失败：{e}", exc_info=True)
        return "未知", "未知", "未知"


def Get_3d_Weather(num: int):
    """获取三天天气
    Args:
        num: 0表示明天，1表示今天
    Returns:
        天气数据字典
    """
    date = time.strftime("%Y-%m-%d", time.localtime())
    clean_weather_key = get_clean_weather_key()
    weather_url = f'{WEATHER_API_BASE_URL}/weather/3d?key={clean_weather_key}&location={CITY_ID}'
    try:
        weather_json = requests.get(weather_url).json()
        logger.debug(f"三天天气API响应: {weather_json}")
        weather_code = weather_json.get("code")
        if weather_code == "200":
            weather_3d = weather_json.get("daily", [])
            for weather in weather_3d:
                if num == 1 and weather.get("fxDate") == date:
                    return weather
                elif num == 0 and weather.get("fxDate") == DATE_TOMORROW:
                    return weather
            logger.warning("未找到匹配的天气数据")
            return {}
        else:
            logger.error(f"访问获取三天天气接口失败，错误码：{weather_code}，响应：{weather_json}")
            return {}
    except Exception as e:
        logger.error(f"获取三天天气失败：{e}", exc_info=True)
        return {}


def Get_today_Weather():
    """获取今日天气数据"""
    weather_text = Get_Weather()[0]
    weather_temp = Get_Weather()[1]
    weather_feels_like = Get_Weather()[2]
    today_json = Get_3d_Weather(1)
    today_sunrise = today_json.get("sunrise", "未知")
    today_sunset = today_json.get("sunset", "未知")
    today_text = today_json.get("textDay", "未知")
    today_temp_high = today_json.get("tempMax", "未知")
    today_temp_low = today_json.get("tempMin", "未知")
    today_humidity = today_json.get("humidity", "未知")
    today_uv_index = today_json.get("uvIndex", "未知")
    
    # 天气提示信息
    weather_greetings = [
        "亲爱的，今天天气",
        "宝贝，今天天气",
        "亲爱的，今日天气",
        "宝贝，今日天气"
    ]
    greeting = random.choice(weather_greetings)
    
    if today_text in RAIN_TYPES:
        if today_text == '大雨':
            weather_text_str = f'\n{greeting}{today_text}，记得带好雨伞🌂，出门注意安全哦～\n'
        elif today_text == '中雨':
            weather_text_str = f'\n{greeting}{today_text}，带把伞出门，别淋着啦～\n'
        elif today_text == '雷阵雨':
            weather_text_str = f'\n{greeting}{today_text}，小心雷声⚡，别怕，我在呢～\n'
        elif today_text == '暴雨':
            weather_text_str = f'\n{greeting}{today_text}，尽量减少外出，出门一定要注意安全～\n'
        elif today_text in ['大暴雨', '特大暴雨']:
            weather_text_str = f'\n{greeting}{today_text}，非常危险⚠️，尽量不要出门，待在安全的地方哦～\n'
        else:
            weather_text_str = f'\n{greeting}{today_text}，出门带伞，注意路况～\n'
    else:
        weather_text_str = f'\n{greeting}{today_text}，天气真不错呢～\n'
    
    # 当前温度提示
    try:
        current_temp = int(weather_temp)
        if current_temp >= 35:
            today_text_str = f"\n{greeting}非常炎热🥵，记得多喝水，做好防暑措施哦～\n"
        elif current_temp >= 30:
            today_text_str = f"\n{greeting}有点热💦，注意防晒，适当补充水分～\n"
        elif current_temp >= 20:
            today_text_str = f"\n{greeting}舒适宜人😊，适合外出活动～\n"
        elif current_temp >= 10:
            today_text_str = f"\n{greeting}有点凉🍂，记得适当添衣～\n"
        else:
            today_text_str = f"\n{greeting}寒冷❄️，一定要穿暖和哦～\n"
    except (ValueError, TypeError):
        today_text_str = f"\n{greeting}，天气不错～\n"
    
    # 紫外线等级提示
    try:
        uv_index = int(today_uv_index)
        if uv_index >= 11:
            today_uv_index_str = "\n紫外线极强😱，避免外出，必须外出时做好全面防晒！"
        elif uv_index >= 8:
            today_uv_index_str = "\n紫外线很强😎，尽量避免长时间户外活动，外出请做好防晒～"
        elif uv_index >= 5:
            today_uv_index_str = "\n紫外线中等☀️，外出建议涂抹防晒霜，戴帽子和太阳镜～"
        elif uv_index >= 3:
            today_uv_index_str = "\n紫外线较弱😌，可以适当外出活动，敏感人群建议防晒～"
        else:
            today_uv_index_str = "\n紫外线很弱🤗，可以放心外出活动～"
    except (ValueError, TypeError):
        today_uv_index_str = "\n紫外线指数未知，外出请注意防护～"
    
    today_text_data = {
        "weather_text": weather_text,
        "weather_temp": weather_temp,
        "weather_feels_like": weather_feels_like,
        "sunrise": today_sunrise,
        "sunset": today_sunset,
        "text": today_text,
        "temp_high": today_temp_high,
        "temp_low": today_temp_low,
        "humidity": today_humidity,
        "uv_index": today_uv_index,
        "weather_text_str": weather_text_str,
        "today_text_str": today_text_str,
        "uv_index_str": today_uv_index_str
    }
    
    return today_text_data


def Get_tomorrow_Weather():
    """获取明日天气数据"""
    tomorrow_json = Get_3d_Weather(0)
    # 明天的天气数据
    tomorrow_sunrise = tomorrow_json.get("sunrise", "未知")
    tomorrow_sunset = tomorrow_json.get("sunset", "未知")
    tomorrow_text = tomorrow_json.get("textDay", "未知")
    tomorrow_temp_high = tomorrow_json.get("tempMax", "未知")
    tomorrow_temp_low = tomorrow_json.get("tempMin", "未知")
    tomorrow_humidity = tomorrow_json.get("humidity", "未知")
    tomorrow_uv_index = tomorrow_json.get("uvIndex", "未知")
    
    # 天气提示信息
    weather_greetings = [
        "亲爱的，明天天气",
        "宝贝，明天天气",
        "亲爱的，明日天气",
        "宝贝，明日天气"
    ]
    greeting = random.choice(weather_greetings)
    
    if tomorrow_text in RAIN_TYPES:
        if tomorrow_text == '大雨':
            tomorrow_text_str = f'\n{greeting}{tomorrow_text}，记得带好雨伞🌂，出门注意安全～\n'
        elif tomorrow_text == '中雨':
            tomorrow_text_str = f'\n{greeting}{tomorrow_text}，带把伞出门，别淋着啦～\n'
        elif tomorrow_text == '雷阵雨':
            tomorrow_text_str = f'\n{greeting}{tomorrow_text}，小心雷声⚡，别怕～\n'
        elif tomorrow_text == '暴雨':
            tomorrow_text_str = f'\n{greeting}{tomorrow_text}，尽量减少外出，出门一定要注意安全～\n'
        elif tomorrow_text in ['大暴雨', '特大暴雨']:
            tomorrow_text_str = f'\n{greeting}{tomorrow_text}，非常危险⚠️，尽量不要出门，待在安全的地方哦～\n'
        else:
            tomorrow_text_str = f'\n{greeting}{tomorrow_text}，出门带伞，注意路况～\n'
    else:
        # 非雨天天气提示
        try:
            temp_high = int(tomorrow_temp_high)
            temp_low = int(tomorrow_temp_low)
            if temp_high >= 35:
                tomorrow_text_str = f"\n{greeting}非常炎热🥵，记得做好防暑措施～\n"
            elif temp_high >= 30:
                tomorrow_text_str = f"\n{greeting}有点热💦，注意防晒和补水～\n"
            elif temp_high >= 25:
                tomorrow_text_str = f"\n{greeting}温暖舒适😊，适合外出活动～\n"
            elif temp_high >= 20:
                tomorrow_text_str = f"\n{greeting}凉爽宜人🍃，记得适当添衣～\n"
            elif temp_high >= 10:
                tomorrow_text_str = f"\n{greeting}有点冷🍂，多穿点衣服哦～\n"
            else:
                tomorrow_text_str = f"\n{greeting}寒冷❄️，一定要穿得厚厚的～\n"
        except (ValueError, TypeError):
            tomorrow_text_str = f"\n{greeting}，天气不错～\n"
    
    tomorrow_text_data = {
        "date": DATE_TOMORROW,
        "text": tomorrow_text,
        "temp_high": tomorrow_temp_high,
        "temp_low": tomorrow_temp_low,
        "humidity": tomorrow_humidity,
        "uv_index": tomorrow_uv_index,
        "sunrise": tomorrow_sunrise,
        "sunset": tomorrow_sunset,
        "weather_text_str": tomorrow_text_str
    }
    
    return tomorrow_text_data

# ----------------------------- 引用语模块 -----------------------------#
# 获取爱情语录
def Get_love(use_local=None):
    """
    获取爱情语录
    :return: 爱情语录内容
    """
    love_quote = [
        "一杯清水，一片面包，一句我爱你，水是你亲手倒的，面包是你亲手切的，我爱你是你亲口对我说的",
        "我会让我的爱陪你慢慢地老去，尽心尽力地去做，能够做到的",
        "想就这样和你相伴到老，把所有不安都忘掉",
        "无论晴天阴天雨天，能收到你的消息的一天就是幸福的一天",
        "一生就这么一次，谈一场以结婚为目的的恋爱吧，不再因为任性而不肯低头，不再因为固执而轻言分手",
        "我没有惊天动地的爱情宣言，也没有海枯石烂的爱情承诺，但是我想告诉你：我比上一秒更爱你",
        "青春里的初恋总是最美却又最伤，因着那份淡淡的情愫，青春有了别样的惆怅滋味",
        "柴米油盐里，藏着对爱情的最好诠释",
        "懂我的人我不需要解释，不懂我的人别看不起人",
        "恋爱就像口香糖，时间长了就索然无味，可不管我们把它丢在哪里都会留下难以抹去的痕迹",
        "这个世界上伤心的人太多，不只你一个，有些事情过去就过去了，永远也不能回头",
        "喜欢你，没有什么特别的理由，就是莫名的觉得好喜欢你",
        "最好的爱情不是完美无憾，而是你来了以后，始终在我身边，再也没走",
        "我能想到最浪漫的事，就是和你一起慢慢变老",
        "爱情不是轰轰烈烈的誓言，而是平平淡淡的陪伴",
        "世界上最美好的事情莫过于，你爱的人正好也爱着你",
        "我愿意用我的一生，换你十年天真无邪",
        "爱是相互的，只有彼此付出，才能长久",
        "遇到你之后，我才知道什么是真正的爱情",
        "和你在一起的每一天，都是我最珍贵的回忆",
        "你的笑容是我见过最美丽的风景",
        "我想和你一起看日出日落，一起走过春夏秋冬",
        "你是我生命中最重要的人，没有之一",
        "我爱你，不是因为你是谁，而是因为和你在一起时我是谁",
        "无论发生什么，我都会在你身边，永远支持你",
        "有你的地方，就是我的家",
        "你是我生命中的一束光，照亮了我的整个世界",
        "我愿意为你做任何事情，只要你开心",
        "和你在一起的时光，是我最快乐的时光",
        "你是我见过最特别的人，我永远不会忘记你",
        "爱情就像一杯咖啡，虽然苦，但是越品越香",
        "我想和你一起慢慢变老，直到我们老得哪也去不了",
        "你是我生命中的奇迹，我会好好珍惜你",
        "我爱你，胜过爱我自己",
        "和你在一起，我感到很安心，很幸福",
        "你是我一生的追求，我会永远爱你",
        "无论遇到什么困难，我们都要一起面对，一起克服",
        "我会一直陪伴着你，直到永远",
        "你是我生命中最美好的相遇",
        "和你在一起，我感到很满足，很快乐",
        "我爱你，不仅因为你的样子，还因为和你在一起时我的样子",
        "你是我生命中的阳光，温暖了我的心",
        "我愿意用我的一生去爱你，保护你",
        "和你在一起，我感到很幸运，很幸福",
        "你是我生命中最重要的人，我会永远珍惜你",
        "我爱你，直到永远",
        "和你在一起的每一天，都是我生命中最美好的一天",
        "你是我生命中的唯一，我会永远爱你",
        "无论发生什么，我都会爱你，永远不变"
    ]
    if love_quote:
        return random.choice(love_quote)
    return "爱的力量是无穷的"

# 获取每日励志语录/中英语
def Get_dailyEnglish(use_local=None):
    """
    获取每日励志语录（中英双语）
    :param use_local: 是否使用本地文案，默认None（使用配置文件设置）
    :return: (中文内容, 英文内容)
    """
    try:
        # 在线获取
        url = 'https://apis.tianapi.com/enmaxim/index?key=' + TIANAPI_KEY
        dailyEnglis = requests.get(url).json()
        dailyEnglis_code = dailyEnglis.get("code")
        if dailyEnglis_code == 200:
            result = dailyEnglis.get("result", {})
            zh = result.get('zh', '')
            en = result.get('en', '')
            
            if zh and en:
                logger.info("获取新的每日英语成功")
                return zh, en
    except Exception as e:
        logger.error(f"获取每日英语失败: {e}")
    return "每一天都是新的开始", "Every day is a new beginning"

# 获取网易云评论


# ----------------------------- 天气数据拼接模块 -----------------------------#
def get_weather_icon(weather_text):
    """根据天气文本获取对应的天气图标
    Args:
        weather_text: 天气文本，如"晴"、"多云"等
    Returns:
        天气图标emoji
    """
    weather_icon_map = {
        "晴": "☀️",
        "多云": "⛅",
        "阴": "☁️",
        "小雨": "🌧️",
        "中雨": "🌧️",
        "大雨": "⛈️",
        "暴雨": "⛈️",
        "雷阵雨": "⛈️",
        "小雪": "❄️",
        "中雪": "❄️",
        "大雪": "❄️",
        "雾": "🌫️",
        "霾": "🌫️",
        "沙尘": "🌪️",
        "大风": "💨"
    }
    # 遍历天气图标映射，找到匹配的图标
    for key, icon in weather_icon_map.items():
        if key in weather_text:
            return icon
    return "🌤️"  # 默认图标


def Splicing_text_data(lz_ch, lz_en, love):
    """拼接文本格式的天气数据
    Args:
        lz_ch: 每日英语中文内容
        lz_en: 每日英语英文内容
        love: 爱情语录内容
    Returns:
        拼接后的文本天气数据
    """
    try:
        global CITY_NAME
        # 初始化默认值，防止None值导致错误
        if lz_ch is None:
            lz_ch = ""
        if lz_en is None:
            lz_en = ""
        if love is None:
            love = ""
        if CITY_NAME is None:
            CITY_NAME = "未知城市"
        
        # 根据时间获取相应的天气数据
        if 0 <= local_time < 18:  # 白天
            today_weather_data = Get_today_Weather()
            if today_weather_data:
                # 构建今天的天气文本
                today_text = (
                    f'{CITY_NAME}天气：\n'
                    f'现在天气：{today_weather_data["weather_text"]}\n\n'
                    f'{today_weather_data["weather_text_str"]}\n\n'
                    f'当前温度：{today_weather_data["weather_temp"]}°C\n\n'
                    f'当前体感温度：{today_weather_data["weather_feels_like"]}°C\n\n'
                    f'湿度：{today_weather_data["humidity"]}%\n\n'
                    f'最高温度：{today_weather_data["temp_high"]}  '
                    f'最低温度：{today_weather_data["temp_low"]}\n\n'
                    f'日出时间：{today_weather_data["sunrise"]} 🌄'
                    f'   日落时间：{today_weather_data["sunset"]} 🌄\n\n'
                    f'{today_weather_data["uv_index_str"]}\n\n'
                    f'{today_weather_data["today_text_str"]}\n\n'
                    f'励志一句：{lz_ch}\n\n{lz_en}\n\n'
                    f'我想对你说：{love}'
                )
                return today_text
            else:
                return "获取今天天气数据失败！"
        elif 19 <= local_time <= 23:  # 晚上七点后
            tomorrow_weather_data = Get_tomorrow_Weather()
            if tomorrow_weather_data:
                # 构建明天的天气文本
                tomorrow_text = (
                    f'{CITY_NAME}天气：\n'
                    f'{tomorrow_weather_data["date"]}\n\n'
                    f'明天天气：{tomorrow_weather_data["text"]}\n\n'
                    f'最高温度：{tomorrow_weather_data["temp_high"]}°C\n\n'
                    f'最低温度：{tomorrow_weather_data["temp_low"]}°C\n\n'
                    f'湿度：{tomorrow_weather_data["humidity"]}%\n\n'
                    f'紫外线强度：{tomorrow_weather_data["uv_index"]}\n\n'
                    f'日出时间：{tomorrow_weather_data["sunrise"]}🌄'
                    f'  日落时间{tomorrow_weather_data["sunset"]}🌇\n\n'
                    f'{tomorrow_weather_data["weather_text_str"]}'
                    f'励志一句：{lz_ch}\n\n{lz_en}\n\n'
                    f'我想对你说：{love}'
                )
                return tomorrow_text
            else:
                return "获取明天天气数据失败！"
        else:
            return "当前时间不在推送范围内"
    except Exception as e:
        logger.error(f"生成天气数据失败：{e}", exc_info=True)
        return f"生成天气数据失败：{e}"


def Splicing_html_data(lz_ch, lz_en, love):
    """拼接HTML格式的天气数据，用于邮件发送
    Args:
        lz_ch: 每日英语中文内容
        lz_en: 每日英语英文内容
        love: 爱情语录内容
    Returns:
        拼接后的HTML天气数据
    """
    try:
        global CITY_NAME
        # 初始化默认值，防止None值导致错误
        if lz_ch is None:
            lz_ch = ""
        if lz_en is None:
            lz_en = ""
        if love is None:
            love = ""
        if CITY_NAME is None:
            CITY_NAME = "未知城市"
        
        # 简单的HTML模板
        html_template = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>天气推送</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f0f2f5;
            margin: 0;
            padding: 0;
            color: #333;
        }
        .container {
            max-width: 600px;
            margin: 20px auto;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }
        .header h1 {
            margin: 0;
            font-size: 24px;
        }
        .content {
            padding: 20px;
        }
        .weather-card {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .weather-card h3 {
            margin-top: 0;
            color: #667eea;
        }
        .weather-overview {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .weather-main {
            display: flex;
            align-items: center;
        }
        .weather-icon {
            font-size: 48px;
            margin-right: 15px;
        }
        .weather-temp {
            font-size: 36px;
            font-weight: bold;
            color: #333;
        }
        .weather-text {
            font-size: 18px;
            color: #666;
        }
        .weather-status {
            text-align: right;
        }
        .weather-status p {
            margin: 5px 0;
            color: #666;
        }
        .weather-details {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }
        .detail-item {
            text-align: center;
            background-color: white;
            padding: 10px;
            border-radius: 6px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }
        .detail-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 5px;
        }
        .detail-value {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }
        .detail-unit {
            font-size: 14px;
            font-weight: normal;
            color: #666;
        }
        .sun-info {
            display: flex;
            justify-content: space-around;
            margin-bottom: 20px;
        }
        .sun-item {
            text-align: center;
        }
        .sun-icon {
            font-size: 24px;
            display: block;
            margin-bottom: 5px;
        }
        .sun-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 5px;
        }
        .sun-time {
            font-size: 16px;
            font-weight: bold;
            color: #333;
        }
        .weather-tip {
            background-color: #e8f4f8;
            padding: 15px;
            border-radius: 6px;
            color: #31708f;
            font-style: italic;
        }
        .quotes-section {
            margin-top: 20px;
            padding: 20px;
            background-color: #f8f9fa;
            border-radius: 8px;
        }
        .quote-item {
            margin-bottom: 15px;
            padding: 15px;
            background-color: white;
            border-radius: 6px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }
        .quote-item h4 {
            margin-top: 0;
            color: #667eea;
            font-size: 16px;
        }
        .quote-content {
            margin: 10px 0;
            line-height: 1.6;
        }
        .footer {
            text-align: center;
            padding: 15px;
            background-color: #f8f9fa;
            border-top: 1px solid #e9ecef;
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔔 每日天气推送 🌟</h1>
        </div>
        <div class="content">
            <h2>📍 {CITY_NAME}</h2>
            {weather_content}
            
            <div class="quotes-section">
                <div class="quote-item">
                    <h4>📖 每日英语</h4>
                    <div class="quote-content">{lz_ch}</div>
                    <div class="quote-content" style="font-style: italic; color: #666;">{lz_en}</div>
                </div>
                
                <div class="quote-item">
                    <h4>💖 爱的告白</h4>
                    <div class="quote-content">{love}</div>
                </div>
                

            </div>
        </div>
        <div class="footer">
            <p>📅 {current_date}</p>
            <p>💌 每日天气推送服务</p>
        </div>
    </div>
</body>
</html>
        """
        
        # 获取当前日期
        current_date = datetime.datetime.now().strftime("%Y年%m月%d日 %H:%M")
        
        # 根据时间获取相应的天气数据，生成动态天气内容
        weather_content = ""
        if 0 <= local_time < 19:  # 白天（0点到19点前）
            today_weather_data = Get_today_Weather()
            if today_weather_data:
                weather_icon = get_weather_icon(today_weather_data['weather_text'])
                # 生成今天的天气HTML内容
                weather_content = f"""
                    <div class="weather-card">
                        <h3>今日天气</h3>
                        
                        <div class="weather-overview">
                            <div class="weather-main">
                                <div class="weather-icon">{weather_icon}</div>
                                <div>
                                    <div class="weather-temp">{today_weather_data['weather_temp']}°C</div>
                                    <div class="weather-text">{today_weather_data['weather_text']}</div>
                                </div>
                            </div>
                            <div class="weather-status">
                                <p>体感温度: {today_weather_data['weather_feels_like']}°C</p>
                                <p>湿度: {today_weather_data['humidity']}%</p>
                            </div>
                        </div>
                        
                        <div class="weather-details">
                            <div class="detail-item">
                                <div class="detail-label">最高温度</div>
                                <div class="detail-value">{today_weather_data['temp_high']}<span class="detail-unit">°C</span></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">最低温度</div>
                                <div class="detail-value">{today_weather_data['temp_low']}<span class="detail-unit">°C</span></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">紫外线</div>
                                <div class="detail-value">{today_weather_data['uv_index']}</div>
                            </div>
                        </div>
                        
                        <div class="sun-info">
                            <div class="sun-item">
                                <span class="sun-icon">🌅</span>
                                <div class="sun-label">日出时间</div>
                                <div class="sun-time">{today_weather_data['sunrise']}</div>
                            </div>
                            <div class="sun-item">
                                <span class="sun-icon">🌇</span>
                                <div class="sun-label">日落时间</div>
                                <div class="sun-time">{today_weather_data['sunset']}</div>
                            </div>
                        </div>
                        
                        <div class="weather-tip">
                            {today_weather_data['weather_text_str']}{today_weather_data['today_text_str']}{today_weather_data['uv_index_str']}
                        </div>
                    </div>
                """
        else:  # 19点后显示明天天气
            tomorrow_weather_data = Get_tomorrow_Weather()
            if tomorrow_weather_data:
                weather_icon = get_weather_icon(tomorrow_weather_data['text'])
                # 生成明天的天气HTML内容
                weather_content = f"""
                    <div class="weather-card">
                        <h3>明日天气</h3>
                        
                        <div class="weather-overview">
                            <div class="weather-main">
                                <div class="weather-icon">{weather_icon}</div>
                                <div>
                                    <div class="weather-text">{tomorrow_weather_data['text']}</div>
                                    <div class="weather-temp">{tomorrow_weather_data['temp_low']}°C ~ {tomorrow_weather_data['temp_high']}°C</div>
                                </div>
                            </div>
                            <div class="weather-status">
                                <p>湿度: {tomorrow_weather_data['humidity']}%</p>
                                <p>紫外线: {tomorrow_weather_data['uv_index']}</p>
                            </div>
                        </div>
                        
                        <div class="sun-info">
                            <div class="sun-item">
                                <span class="sun-icon">🌅</span>
                                <div class="sun-label">日出时间</div>
                                <div class="sun-time">{tomorrow_weather_data['sunrise']}</div>
                            </div>
                            <div class="sun-item">
                                <span class="sun-icon">🌇</span>
                                <div class="sun-label">日落时间</div>
                                <div class="sun-time">{tomorrow_weather_data['sunset']}</div>
                            </div>
                        </div>
                        
                        <div class="weather-tip">
                            {tomorrow_weather_data['weather_text_str']}
                        </div>
                    </div>
                """
        
        # 替换HTML模板中的所有占位符
        html_content = html_template.replace('{CITY_NAME}', CITY_NAME)
        html_content = html_content.replace('{current_date}', current_date)
        html_content = html_content.replace('{weather_content}', weather_content)
        html_content = html_content.replace('{lz_ch}', lz_ch)
        html_content = html_content.replace('{lz_en}', lz_en)
        html_content = html_content.replace('{love}', love)
        
        return html_content
    except Exception as e:
        logger.error(f"生成HTML天气数据失败：{e}", exc_info=True)
        return f"生成天气数据失败：{e}"

# ----------------------------- 推送服务模块 -----------------------------#
def ServerChan_Push(lz_ch, lz_en, love):
    """Server酱消息推送APP"""
    try:
        title = '🔔查收天气情况🌟'
        content = Splicing_text_data(lz_ch, lz_en, love)
        # 调用Server酱API
        url = f"https://sctapi.ftqq.com/{SENDKEY}.send"
        data = {
            "title": title,
            "desp": content,
            "channel": 9
        }
        response = requests.post(url, data=data)
        result = response.json()
        if result.get("code") == 0:
            logger.info("Server酱消息推送成功!")
        else:
            logger.error(f"Server酱消息推送失败: {result}")
    except Exception as e:
        logger.error(f"Server酱消息推送失败!,失败原因: {e}", exc_info=True)


def Send_Email(to_emails, lz_ch, lz_en, love):
    """发送邮件，支持多个收件人
    to_emails: 收件人列表或逗号分隔的字符串
    """
    subject = Header('🔔查收天气情况🌟', 'utf-8').encode()  # 邮件标题
    # 创建邮件对象
    msg = MIMEMultipart()
    msg['From'] = EMAIL
    
    # 处理收件人
    if isinstance(to_emails, str):
        # 如果是字符串，按逗号分隔转换为列表
        to_emails = [email.strip() for email in to_emails.split(',') if email.strip()]
    elif not isinstance(to_emails, list):
        # 如果既不是字符串也不是列表，转换为列表
        to_emails = [to_emails]
    
    # 设置邮件头，用逗号分隔显示所有收件人
    msg['To'] = ','.join(to_emails)
    msg['Subject'] = subject
    
    # 添加邮件正文
    try:
        # 使用Splicing_html_data函数生成HTML内容
        html_content = Splicing_html_data(lz_ch, lz_en, love)
        msg.attach(MIMEText(html_content, 'html', 'utf-8'))
    except Exception as e:
        logger.error(f"生成邮件内容失败: {e}", exc_info=True)
        return

    try:
        logger.info(f"正在连接SMTP服务器: {SMTP_SERVER}:{SMTP_PORT}")
        # 连接到SMTP服务器
        server = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT, timeout=10)  # 添加超时设置
        logger.info(f"成功连接到SMTP服务器: {SMTP_SERVER}:{SMTP_PORT}")
        
        # 登录到SMTP服务器
        server.login(EMAIL, EMAIL_PASSWORD)
        logger.info("成功登录SMTP服务器")

        # 发送邮件，sendmail函数接受收件人列表
        server.sendmail(EMAIL, to_emails, msg.as_string())
        server.quit()
        logger.info(f"邮件投递成功! 收件人: {','.join(to_emails)}")
    except smtplib.SMTPConnectError as e:
        logger.error(f"连接SMTP服务器失败: {e}", exc_info=True)
    except smtplib.SMTPAuthenticationError as e:
        logger.error(f"SMTP服务器认证失败: {e}", exc_info=True)
    except smtplib.SMTPException as e:
        logger.error(f"SMTP服务器错误: {e}", exc_info=True)
    except Exception as e:
        logger.error(f"邮件投递失败,失败原因: {e}, 类型: {type(e).__name__}", exc_info=True)

# ----------------------------- 主程序 -----------------------------#
if __name__ == '__main__':
    # 只调用一次引用语函数，获取结果
    lz_ch, lz_en = Get_dailyEnglish()
    love = Get_love()
    
    # 将结果传递给推送函数
    ServerChan_Push(lz_ch, lz_en, love)
    # 支持多个收件人，可以传入列表或逗号分隔的字符串
    Send_Email(["zian5210@163.com"], lz_ch, lz_en, love)
